//
//  ITShowImageView.m
//  Seven
//
//  Created by admin on 2019/12/22.
//  Copyright © 2016年 Seven. All rights reserved.
//

#import <Accelerate/Accelerate.h>
#import "ITShowImageView.h"
#import "ITCropImageView.h"
#pragma mark - MaskShadowLyer

@interface MaskShadowLyer ()

@property (nonatomic, strong)CALayer *scaleIcon;
@end

@implementation MaskShadowLyer

- (instancetype)initWithRaidus:(CGFloat)radius type:(ClipType)type shapeSize:(CGSize)shapSize viewSize:(CGSize)viewSize {
    self = [super init];
    if (self) {
        _viewSize = viewSize;
        _clipType = type;
        _clipSize = shapSize;
        _clipRadius = radius;
        [self updateLayerPath];
        //默认颜色
        self.fillColor = [UIColor colorWithWhite:1 alpha:1].CGColor;
    }
    return self;
}

- (void)setClipType:(ClipType)clipType{
    if (_clipType == clipType) {
        return;
    }
    _clipType = clipType;
    [self updateLayerPath];
}
- (void)setViewSize:(CGSize)viewSize{
    if (CGSizeEqualToSize(_viewSize, viewSize)) {
        return;
    }
    _viewSize = viewSize;
    [self updateLayerPath];
}
- (void)setClipSize:(CGSize)clipSize{
    if (CGSizeEqualToSize(_clipSize, clipSize)) {
        return;
    }
    _clipSize = clipSize;
    [self updateLayerPath];
}

- (void)setClipRadius:(CGFloat)clipRadius{
    if (_clipRadius == clipRadius) {
        return;
    }
    _clipRadius = clipRadius;
    [self updateLayerPath];
}

- (void)updateLayerPath{
    CGRect rect = CGRectMake(0, 0, _viewSize.width, _viewSize.width);
    self.bezierPath = [UIBezierPath bezierPathWithRect:rect];
    
    CGFloat rectX = (rect.size.width-_clipSize.width)/2;
    CGFloat rectY = (rect.size.height-_clipSize.height)/2;
    CGFloat rectW = _clipSize.width;
    CGFloat rectH = _clipSize.height;
    
    CGRect cropRect = CGRectMake(rectX, rectY, rectW, rectH);
    CGFloat radius = self.clipType == ClipTypeRect? self.clipRadius : rectW/2;
    if (self.clipType == ClipTypeEllipse){
        CGPathRef path = CGPathCreateWithEllipseInRect(cropRect, NULL);
        [_bezierPath appendPath:[[UIBezierPath bezierPathWithCGPath:path] bezierPathByReversingPath]];
        CGPathRelease(path);
        
    }else {
        [_bezierPath appendPath:[[UIBezierPath bezierPathWithRoundedRect:cropRect cornerRadius:radius] bezierPathByReversingPath]];
    }
    
    self.path = _bezierPath.CGPath;
    
    if (_showCropLine) {
        
        /*
        CGFloat tmpWidth = 40.0;
        CGFloat num = 4.0;
        CGFloat length = radius*2.0*M_PI;
        CGFloat space = (length - tmpWidth*num)/num;
        //[_cropLine setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:tmpWidth], [NSNumber numberWithInt:space], nil]];
         //*/
        /*
        CGFloat centerX = _viewSize.width/2;
        CGFloat centerY = _viewSize.height/2;
        
        CGPoint center = CGPointMake(centerX, centerY);
        
        CGFloat angle = M_PI/16.0  * _viewSize.width/rectW;
        
        CGFloat startAngle = -(M_PI_2-angle)/2;
        
        UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startAngle endAngle:startAngle-angle clockwise:NO];
        
        startAngle -= M_PI/2;
        [path appendPath:[UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startAngle endAngle:startAngle-angle clockwise:NO]];
        
        startAngle -= M_PI/2;
        [path appendPath:[UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startAngle endAngle:startAngle-angle clockwise:NO]];
        
        startAngle -= M_PI/2;
        [path appendPath:[UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startAngle endAngle:startAngle-angle clockwise:NO]];
        
        _cropLine.path = path.CGPath;
         //*/
        //*
        CGFloat tmp = cropRect.size.width+_cropLine.lineWidth/2 - _viewSize.width;
        if (tmp>0) {
            cropRect = CGRectInset(cropRect, tmp, tmp);
        }
        CGFloat moveOffset = CGRectGetMidX(cropRect)+radius/sqrtf(2);
        CGFloat offset = moveOffset + 8;
        
        [CATransaction begin];
        [CATransaction setDisableActions:YES];
        _scaleIcon.frame = CGRectMake(offset, offset, 24, 24);
        [CATransaction commit];
        
        offset += 5;
        CGMutablePathRef  path =  CGPathCreateMutable();
        CGPathMoveToPoint(path, nil, moveOffset, moveOffset);
        CGPathAddLineToPoint(path, nil, offset, offset);
        CGPathAddEllipseInRect(path, nil, cropRect);
        //CGPathCloseSubpath(path);
        _cropLine.path = path;
        CGPathRelease(path);
         //*/
    }
}

- (CGPathRef)layerPath{
    if (_layerPath == nil) {
        CGMutablePathRef path = CGPathCreateMutable();
        CGRect rect = CGRectMake(0, 0, _viewSize.width, _viewSize.width);
        CGPathAddRect(path, NULL, rect);
        CGFloat rectX = (rect.size.width-_clipSize.width)/2;
        CGFloat rectY = (rect.size.height-_clipSize.height)/2;
        CGFloat rectW = _clipSize.width;
        CGFloat rectH = _clipSize.height;
        if (self.clipType == ClipTypeCycle) {
            CGPathAddArc(path, NULL, rectX, rectY, rectW, 0, M_PI*2, NO);
        } else if (self.clipType == ClipTypeRect) {
            if (_clipRadius==0) {
                CGPathAddRect(path, NULL, CGRectMake(rectX, rectY, rectW, rectH));
            }else {
                UIBezierPath *maskPath =
                [UIBezierPath bezierPathWithRoundedRect:CGRectMake(rectX, rectY, rectW, rectH)
                                      byRoundingCorners:UIRectCornerAllCorners
                                            cornerRadii:CGSizeMake(_clipRadius, _clipRadius)];
                //_layerPath = maskPath.CGPath;
                CGPathAddPath(path, NULL, maskPath.CGPath);
            }
        } else  if (self.clipType == ClipTypeEllipse){
            CGPathAddEllipseInRect(path, NULL, CGRectMake(rectX, rectY, rectW, rectH));
        }
        _layerPath = path;
    }
    return _layerPath;
}

#pragma mark cropLine
- (void)setCropLineWidth:(CGFloat)cropLineWidth{
    if (_cropLineWidth == cropLineWidth) {
        return;
    }
    _cropLineWidth = cropLineWidth;
    if (_showCropLine) {
        [self updateLayerPath];
    }
}
- (void)setCropLineColor:(UIColor *)cropLineColor{
    if (_cropLineColor == cropLineColor) {
        return;
    }
    _cropLineColor = cropLineColor;
    
    if (_showCropLine) {
        [self updateLayerPath];
    }
}

- (void)setShowCropLine:(BOOL)showCropLine{
    if (_showCropLine == showCropLine) {
        return;
    }
    _showCropLine = showCropLine;
    if (_showCropLine) {
        if (!_cropLine) {
            self.cropLine = [CAShapeLayer layer];
            _cropLine.frame = self.bounds;
            _cropLine.fillColor = [UIColor clearColor].CGColor;
            _cropLine.strokeColor = _cropLineColor ? _cropLineColor.CGColor : [UIColor colorWithWhite:1 alpha:0.5].CGColor;
            _cropLine.lineWidth = _cropLineWidth ?: 2;
            //_cropLine.masksToBounds = YES;
            [self.superlayer addSublayer:_cropLine];
            
            _scaleIcon = [CALayer layer];
            _scaleIcon.contents = (id)[UIImage imageNamed:@"scale_icon"].CGImage;
            _scaleIcon.contentsScale = [UIScreen mainScreen].scale;
            [_cropLine addSublayer:_scaleIcon];
        }
        _cropLine.hidden = NO;
        [self updateLayerPath];
    }else {
        _cropLine.hidden = YES;
    }
}
@end


@interface ITShowImageView() <UIScrollViewDelegate, UIGestureRecognizerDelegate>{
    CGFloat _lastRotation;
    CGFloat _currentRotation;
    
    CGPoint _lastPoint;
    CGFloat _lastScale;
    
    BOOL _isDoubleTap;
    
    CGPoint _doubleTapPoint;
    
    CGFloat _halfAppendWidth;
    
    CGFloat _lastTransformScale;
    CGAffineTransform _lastTransform;
    CGAffineTransform _defaultTransform;
    
    CGFloat _unLimitLastScale;
    CGPoint _unLimitLastOffset;
    
    BOOL _fullContent;
    BOOL _hasDoubleClicked;
}
@property (nonatomic, strong) UIRotationGestureRecognizer *rotateGesture;
@property (nonatomic, strong) UIPanGestureRecognizer *panGesture;
@property (nonatomic, strong) UIPinchGestureRecognizer *pinchGesture;
@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGesture;

@end
@implementation ITShowImageView
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initView];
    }
    return self;
}
- (void)dealloc{
    //[self removeObserverBlocks];
}


- (void)setBackgroundColor:(UIColor *)backgroundColor{
    [super setBackgroundColor:backgroundColor];
    _zoomScrollView.backgroundColor = backgroundColor;
    _zoomImageView.backgroundColor = backgroundColor;
}

- (void)initView{
    _maskWidth = CGRectGetWidth(self.bounds)-30;
    CGAffineTransform transform = CGAffineTransformMakeRotation(0);
    transform = CGAffineTransformScale(transform, 1, 1);
    _defaultTransform = transform;
    _lastTransform = transform;
    
    _unLimitBackgroundColor = [UIColor whiteColor];
    //self.backgroundColor = [UIColor whiteColor];
    //self.backgroundColor = COLOR_3c3c3c;
    //self.clipsToBounds = NO;
    self.clipRect = self.bounds;
    [self addSubview:self.zoomScrollView];
    [self.zoomScrollView addSubview:self.zoomImageView];
//    @weakify(self);
//    [self addObserverBlockForKeyPath:@"frame" block:^(id  _Nonnull obj, id  _Nonnull oldVal, id  _Nonnull newVal) {
//        @strongify(self);
//        CGRect old = [oldVal CGRectValue];
//        CGRect new = [newVal CGRectValue];
//        if (!CGSizeEqualToSize(old.size, new.size)) {
//            [self updateZoomViews];
//        }
//    }];
    
    [self addDoubleTapGesture];
}


#pragma mark - updateZoomView
- (void)updateZoomViews{
    if (_image == nil) {
        return;
    }
    _hasDoubleClicked = NO;
    //更新frame/切换图片后 重需要重置
    _zoomScrollView.transform = CGAffineTransformMakeRotation(0);
    CGAffineTransform transform = CGAffineTransformIdentity;
    transform = CGAffineTransformMakeScale(1, 1);
    //transform = CGAffineTransformRotate(transform, 0);//旋转要不要重置?
    _zoomImageView.transform = transform;
    
    if (_newUnLimit) {//两种结构不通 单独配置
        _zoomImageView.transform = CGAffineTransformMakeScale(1, 1);
        _zoomImageView.transform = CGAffineTransformMakeRotation(0);
        CGFloat widthScale = self.frame.size.width / _image.size.width;
        CGFloat heightScale = self.frame.size.height / _image.size.height;
        
        CGFloat toScale = MIN(widthScale, heightScale)/2;
        CGRect imageBounds = CGRectMake(0, 0, _image.size.width*toScale, _image.size.height*toScale);
        _zoomImageView.frame = imageBounds;
        //[_zoomImageView centerToParent];
        return;
    }
    //CGSize lSize = self.bounds.size;
    //self.clipRect = CGRectMake((self.frame.size.width-lSize.width)/2, (self.frame.size.height-lSize.height)/2, lSize.width, lSize.height);
    
    CGRect rect = self.bounds;
    if (_limitCycle) {
        self.clipRect = CGRectMake(DefaultCycleOffset, DefaultCycleOffset, rect.size.width-DefaultCycleOffset*2, rect.size.width-DefaultCycleOffset*2);
    }else {
        self.clipRect = rect;
    }
    _zoomScrollView.bounds = CGRectMake(0, 0, _clipRect.size.width, _clipRect.size.height);
    
    CGFloat widthScale = self.clipRect.size.width / self.zoomImageView.frame.size.width;
    CGFloat heightScale = self.clipRect.size.height / self.zoomImageView.frame.size.height;
    
    
    _maxCurrScale = MAX(widthScale, heightScale);
    _minCurrScale = MIN(widthScale, heightScale);
    
    CGFloat minScale = _minScale ?: _minCurrScale;
    
    _lastScale  = _maxCurrScale;
    
    //_lastScale 首次展示倍数
    if (_unLimit) {// 无限制
        _zoomScrollView.decelerationRate = UIScrollViewDecelerationRateFast;
        //_lastScale = _minCurrScale*.75;//首次显示 1/2;
        _lastScale = _maxCurrScale;
        minScale = _minCurrScale/20.0;//无限制
        self.backgroundColor = self.unLimitBackgroundColor;
    }else {
        _zoomScrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
        //self.backgroundColor = _showFullImage ? [UIColor whiteColor] : [UIColor blackColor];
        //self.backgroundColor = _cropChangeEnable ? [UIColor blackColor] : [UIColor whiteColor];
        
        //首次显示撑满  最后执行.
        if (_showFullImage) {//显示全部图片 选择小的倍数
            _lastScale = _minScale;
        }else if(_limitCycle){//限制圆要放大倍数
            minScale = _maxCurrScale;
            _lastScale = minScale*self.bounds.size.width/_clipRect.size.width;
        }else {//撑满视图 max
            minScale = _maxCurrScale;
            _lastScale = minScale;
        }
    }
    [_zoomScrollView setMaximumZoomScale:_maxCurrScale*3.0];
    [_zoomScrollView setMinimumZoomScale:minScale];
    
    _zoomScrollView.zoomScale = _lastScale;
    
    [self scrollViewDidZoom:_zoomScrollView];
    
    
    if (_cropChangeEnable) {
        [_zoomScrollView setMaximumZoomScale:CGFLOAT_MAX];
    }
    if (!_showFullImage) {
        //移动到中央
        [self moveImageToCenterWithAnimation:NO];
    }
}

- (void)updateItemLimit{
    if (!_newUnLimit) {
        return;
    }
    //[self edgeLimitSubview:_zoomImageView offset:10];
    
     //*/
}
- (void)setCropChangeEnable:(BOOL)cropChangeEnable{
    if (_cropChangeEnable == cropChangeEnable) {
        return;
    }
    _cropChangeEnable = cropChangeEnable;
    [self updateZoomViews];
}

- (CGRect)getScrollRectWithCropRect:(CGRect)rect{
    CGPoint left_top = [self convertPoint:rect.origin fromView:self.superview];
    CGPoint right_top = [self convertPoint:CGPointMake(CGRectGetMaxX(rect), rect.origin.y) fromView:self.superview];
    CGPoint left_bottom = [self convertPoint:CGPointMake(rect.origin.x, CGRectGetMaxY(rect)) fromView:self.superview];
    CGPoint right_bottom = [self convertPoint:CGPointMake(CGRectGetMaxX(rect), CGRectGetMaxY(rect)) fromView:self.superview];
    
    CGFloat top = MIN( MIN(left_top.y, right_top.y),  MIN(left_bottom.y, right_bottom.y));
    CGFloat bottom = MAX( MAX(left_top.y, right_top.y),  MAX(left_bottom.y, right_bottom.y));
    CGFloat left = MIN( MIN(left_top.x, right_top.x),  MIN(left_bottom.x, right_bottom.x));
    CGFloat right = MAX( MAX(left_top.x, right_top.x),  MAX(left_bottom.x, right_bottom.x));
    
    CGRect theRect = CGRectMake(left, top, right - left, bottom - top);
    return theRect;
}

- (void)updateCropRect:(CGRect)rect reset:(BOOL)reset change:(void (^)(void))change{
    self.clipRect = rect;
    if (reset) {
        /*
        //更新frame/切换图片后 重需要重置 重置会有跳跃
        CGAffineTransform transform = CGAffineTransformIdentity;
        transform = CGAffineTransformMakeScale(1, 1);
        transform = CGAffineTransformRotate(transform, 0);//旋转要不要重置?
        _zoomImageView.transform = transform;
        //*/
        //_zoomScrollView.bounds = CGRectMake(0, 0, _clipRect.size.width, _clipRect.size.height);
        
        CGFloat widthScale = self.clipRect.size.width / self.zoomImageView.frame.size.width;
        CGFloat heightScale = self.clipRect.size.height / self.zoomImageView.frame.size.height;
        
        
        CGFloat tmpScale = MAX(widthScale, heightScale) * _zoomScrollView.zoomScale;
        //缩放居中
        [_zoomScrollView setZoomScale:tmpScale animated:NO];
        
        _zoomScrollView.frame = rect;
        //* 缩放图片
        CGRect imageRect = _zoomScrollView.bounds;
        CGFloat wScale = imageRect.size.width/_image.size.width;
        CGFloat hScale = imageRect.size.height/_image.size.height;
        CGFloat theScale = MAX(wScale, hScale);
        imageRect.size.width = theScale*_image.size.width;
        imageRect.size.height = theScale*_image.size.height;
        imageRect.origin = CGPointZero;
        _zoomImageView.frame = imageRect;
        _zoomScrollView.contentSize = imageRect.size;
         //*/
        [self moveImageToCenterWithAnimation:NO];
        [_zoomScrollView setMinimumZoomScale:_zoomScrollView.zoomScale];
    }else {
        if (_lastRotation == 0 || _cropView.cycleMaskEnable) {
            _zoomScrollView.frame = rect;
            if (change) {
                change();
            }
        }else{
            _zoomScrollView.frame = [self getScrollRectWithCropRect:rect];
            
            /*
            CGFloat width = _clipRect.size.width;
            CGFloat height = _clipRect.size.height;
            CGFloat theDiameterLength = sqrt(width*width + height*height);
            CGFloat theAngleWH = atan(width/height);
            CGFloat theAngleHW = atan(height/width);
            
            CGFloat toWidth = cos(_currentRotation-theAngleHW)*theDiameterLength;
            CGFloat toHeight = cos(theAngleWH - _currentRotation)*theDiameterLength;
            
            //_zoomScrollView.transform = _defaultTransform;
            
            CGRect frame = _zoomScrollView.bounds;
            frame.size = CGSizeMake(toWidth, toHeight);
            _zoomScrollView.bounds = frame;
            //*/
            if (change) {
                change();
            }
            //_zoomScrollView.transform = _lastTransform;
        }
    }
}
- (void)updateImage:(UIImage *)image{
    self.image = image;
    //*
    if (_unLimit) {
        _autoAdsorptionEdge = NO;
        CGFloat lastScale = _minCurrScale*.75;
        [_zoomScrollView setZoomScale:lastScale animated:NO];
        //[_zoomScrollView setContentOffset:lastPoint animated:NO];
        //默认居中
        [self moveImageToCenterWithAnimation:NO];
        _autoAdsorptionEdge = NO;
//        custom_dispatch_after(.3, ^{
//            _autoAdsorptionEdge = YES;
//        });
    }//*/
}
- (void)onlyChangeImage:(UIImage *)image{//只是改变图片
    _image = image;
    self.zoomImageView.image = image;
    BOOL adsorptionEdge = _autoAdsorptionEdge;
     _autoAdsorptionEdge = NO;
    [self updateBlurShadow];
    _autoAdsorptionEdge = adsorptionEdge;
    
    //[self addFadeAnimation];
}
#pragma mark - open method
- (void)moveImageToCenterWithAnimation:(BOOL)animation{
    CGFloat offsetX = (_zoomScrollView.contentSize.width-_zoomScrollView.frame.size.width)/2;
    CGFloat offsetY = (_zoomScrollView.contentSize.height-_zoomScrollView.frame.size.height)/2;
    [self.zoomScrollView setContentOffset:CGPointMake(offsetX, offsetY) animated:animation];
}

- (UIImage *)outputImage{
    UIImage *cropImage = nil;
    UIImage *handleImage = self.zoomImageView.image;
    
    CGFloat scale = 1;
    
    //*
    if (_unLimit) {
        /*
        scale = handleImage.size.width/(_zoomScrollView.contentSize.width-_halfAppendWidth*2);
        
        CGFloat x = MAX(0, (_zoomScrollView.contentOffset.x-_halfAppendWidth)*scale);
        CGFloat y = MAX(0, (_zoomScrollView.contentOffset.y-_halfAppendWidth)*scale);
        
        CGFloat w = CGRectGetWidth(_zoomImageView.frame)-x;
        CGFloat h = CGRectGetHeight(_zoomImageView.frame)-y;
        
        CGFloat spaceW = (CGRectGetMaxX(_zoomImageView.frame) - (_zoomScrollView.contentOffset.x + self.width));
        if (spaceW>0) {
            w -= spaceW;
        }
        
        CGFloat spaceH = (CGRectGetMaxY(_zoomImageView.frame) - (_zoomScrollView.contentOffset.y + self.height));
        if (spaceH>0) {
            h -= spaceH;
        }
        CGRect cropRect = CGRectMake(x, y, w*scale, h*scale);
        cropImage = [handleImage cropImageInRect:cropRect];
        //*/
        
        //创建画布size 高保真的话增加放大倍数 最大倍数为 self.image.size.width/self.zoomImageView.size.width
        //*
        //限制最大倍数? 需要?
        scale = handleImage.size.width/self.zoomImageView.frame.size.width;
        if (scale < [UIScreen mainScreen].scale) {
            scale = [UIScreen mainScreen].scale;
        }
        
        CGFloat imageWidth = lroundf(CGRectGetWidth(self.frame)*scale);
        if (imageWidth > DefaultMaxWidth) {
            //防止生成图片过大
            imageWidth = DefaultMaxWidth;
            scale = imageWidth/CGRectGetWidth(self.frame);
        }
        //取的坐标系是基于self.view的 所以放大要基于self的frame放大
        
        CGRect drawRect = CGRectMake((_zoomImageView.frame.origin.x - _zoomScrollView.contentOffset.x), (_zoomImageView.frame.origin.y - _zoomScrollView.contentOffset.y), self.zoomImageView.frame.size.width, self.zoomImageView.frame.size.height);
        
        drawRect.origin.x = lroundf(drawRect.origin.x*scale);
        drawRect.origin.y = lroundf(drawRect.origin.y*scale);
        drawRect.size.width = lroundf(drawRect.size.width*scale);
        drawRect.size.height = lroundf(drawRect.size.height*scale);
        
        
        //UIGraphicsBeginImageContext(CGSizeMake(imageWidth, imageWidth));
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageWidth, imageWidth), NO, handleImage.scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        //绘制背景颜色
        /*
        UIImage *backgroundImg = nil;
        switch (_secondOptionType) {
            case EditOptionTypeAlpha: case EditOptionTypeBlack:{
                //CGContextSetFillColorWithColor(context, self.backgroundColor.CGColor);
                //CGContextFillRect(context, CGRectMake(0, 0, imageWidth, imageWidth));
                BOOL black = self.shadowColor == COLOR_BLACK;
                if (_secondOptionType == EditOptionTypeBlack){
                    [MobClick event:@"square_save" label:black?@"黑":@"白"];
                }else {
                    [MobClick event:@"square_save" label:black?@"透明黑":@"透明白"];
                }
            }
                break;
            case EditOptionTypeXuan1:{
                backgroundImg = [UIImage imageNamed:@"xuanpaper_larger" cached:NO];
                [MobClick event:@"square_save" label:@"牙色"];
            }
                break;
            case EditOptionTypeXuan2:{
                backgroundImg = [UIImage imageNamed:@"xuanpaper2_larger" cached:NO];
                [MobClick event:@"square_save" label:@"水墨"];
            }
                break;
            case EditOptionTypeXuan3:{
                backgroundImg = [UIImage imageNamed:@"xuanpaper3_larger" cached:NO];
                [MobClick event:@"square_save" label:@"茶白"];
            }
                break;
                
            default:
                break;
        }//*/
        
        CGContextSetFillColorWithColor(context, self.backgroundColor.CGColor);
        CGContextFillRect(context, CGRectMake(0, 0, imageWidth, imageWidth));
        
        [handleImage drawInRect:drawRect];
        cropImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return cropImage;
    }
    //*/
    
    scale = handleImage.size.width/_zoomScrollView.contentSize.width;
    CGFloat offsetScale = 1;
    CGFloat offset = _limitCycle ? DefaultCycleOffset : 0;
    
    CGRect cropRect = CGRectMake(_zoomScrollView.contentOffset.x-offset, _zoomScrollView.contentOffset.y-offset, self.clipRect.size.width+offset*2, self.clipRect.size.height+offset*2);
    
    cropRect.size.width = lroundf(cropRect.size.width*scale);
    cropRect.size.height = lroundf(cropRect.size.height*scale);
    
    cropRect.origin.x = lroundf(cropRect.origin.x*scale);
    cropRect.origin.y = lroundf(cropRect.origin.y*scale);
    
    CGFloat rotate = atan2(self.transform.b, self.transform.a);//;
    
    CGSize contentSize = CGSizeMake(cropRect.size.width*offsetScale, cropRect.size.height*offsetScale);
    //UIGraphicsBeginImageContext(contentSize);
    UIGraphicsBeginImageContextWithOptions(contentSize, NO, handleImage.scale);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //透明会影响模糊效果.
    //绘制背景颜色
    CGContextSetFillColorWithColor(context, self.backgroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0, 0, contentSize.width, contentSize.height));
    
    if (rotate != 0) {
        CGPoint center = CGPointMake(cropRect.size.width/2, cropRect.size.height/2);
        //以中心点旋转 然后回到原点
        CGContextConcatCTM(context, CGAffineTransformMakeTranslation(center.x, center.y));
        CGContextConcatCTM(context, CGAffineTransformMakeRotation(rotate));
        CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-center.x, -center.y));
    }
    CGRect drawRect = CGRectMake(-cropRect.origin.x, -cropRect.origin.y, handleImage.size.width , handleImage.size.height);
    
    
    [handleImage drawInRect:drawRect];
    
    cropImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return cropImage;
}

- (void)fillShadowWithColor:(UIColor *)color image:(UIImage *)image{
    //直接改变fillcolur 会有白屏闪烁 所以直接添加新的 再移除老的.
    
    MaskShadowLyer *_layer = [[MaskShadowLyer alloc] initWithRaidus:0 type:ClipTypeCycle shapeSize:CGSizeMake(_maskWidth, _maskWidth) viewSize:self.bounds.size];
    
    if (image){//图片优先
        _layer.fillColor = [UIColor colorWithPatternImage:image].CGColor;
    }else if (color) {
        _layer.fillColor = color.CGColor;
    }else {
        _layer.fillColor = [UIColor colorWithWhite:1 alpha:1].CGColor;
    }
    //背景颜色调整
    if (color == [UIColor blackColor]) {
        self.backgroundColor = color;
    }else {
        self.backgroundColor = [UIColor whiteColor];
    }
    
    [self.layer addSublayer:_layer];
    if (_shadowLayer) {//如果有先移除
        [_shadowLayer removeFromSuperlayer];
        _shadowLayer = nil;
    }
    self.shadowLayer = _layer;
}
- (void)copyToOtherView:(ITShowImageView *)view{
    //view.zoomImageView.transform = _zoomImageView.transform;
    view.zoomScrollView.zoomScale = _zoomScrollView.zoomScale;
    view.zoomScrollView.contentOffset = _zoomScrollView.contentOffset;
}

- (void)adsorptionEdge{//吸附边界
    if (!_autoAdsorptionEdge) {
        return;
    }
    CGFloat offsetX = 0, offsetY = 0;
    BOOL shouldChangeOffset = NO;
    
    //*
    offsetX = _zoomScrollView.contentOffset.x;
    offsetY = _zoomScrollView.contentOffset.y;
    
    //FIXME:自动吸附 左上角 对齐小格子左上角.  默认 6X6 鸽子 如果有旋转角度的话 如何处理
    //相对父视图原点位置
    CGFloat tmpSpace = KScreenWidth/6.0;
    CGFloat tmpSpace1 = AutoAnchorOffsetSpace;
    CGFloat tmpSpace2 = tmpSpace-tmpSpace1;
    CGFloat width = self.bounds.size.width;
    CGFloat height = self.bounds.size.height;
    //左上角
    CGFloat tmpX = _zoomImageView.frame.origin.x - offsetX;
    CGFloat tmpY = _zoomImageView.frame.origin.y - offsetY;
    
    CGFloat tmpX2 = tmpX + _zoomImageView.width;
    CGFloat tmpY2 = tmpY + _zoomImageView.height;
    
    
    //中间的点
    CGFloat tmpX3 = tmpX + _zoomImageView.width/2;
    CGFloat tmpY3 = tmpY + _zoomImageView.height/2;
    
    if (tmpX > width) {
        tmpX = 0;
    }
    while (tmpX>tmpSpace) {
        tmpX -= tmpSpace;
    }
    if (tmpX>0 && tmpX<tmpSpace1) {
        tmpX = -tmpX;
    }else if (tmpX>tmpSpace2){
        tmpX = tmpSpace - tmpX;
    }else {
        tmpX = 0;
    }
    
    if (tmpX2 > width) {
        tmpX2 = 0;
    }
    while (tmpX2>tmpSpace) {
        tmpX2 -= tmpSpace;
    }
    if (tmpX2>0 && tmpX2<tmpSpace1) {
        tmpX2 = -tmpX2;
    }else if (tmpX2>tmpSpace2){
        tmpX2 = tmpSpace - tmpX2;
    }else {
        tmpX2 = 0;
    }
    
    if (tmpY > height) {
        tmpY = 0;
    }
    while (tmpY>tmpSpace) {
        tmpY -= tmpSpace;
    }
    if (tmpY>0 && tmpY<tmpSpace1) {
        tmpY = -tmpY;
    }else if (tmpY>tmpSpace2){
        tmpY = tmpSpace - tmpY;
    }else {
        tmpY = 0;
    }
    
    if (tmpY2 > height) {
        tmpY2 = 0;
    }
    while (tmpY2>tmpSpace) {
        tmpY2 -= tmpSpace;
    }
    if (tmpY2>0 && tmpY2<tmpSpace1) {
        tmpY2 = -tmpY2;
    }else if (tmpY2>tmpSpace2){
        tmpY2 = tmpSpace - tmpY2;
    }else {
        tmpY2 = 0;
    }
    
    if (tmpX2 !=0 && (fabs(tmpX2) < fabs(tmpX) || tmpX == 0)) {
        tmpX = tmpX2;
    }
    if (tmpY2 !=0 && (fabs(tmpY2) < fabs(tmpY) || tmpY == 0)) {
        tmpY = tmpY2;
    }
    
    if (tmpX3 > width) {
        tmpX3 = 0;
    }
    while (tmpX3>tmpSpace) {
        tmpX3 -= tmpSpace;
    }
    if (tmpX3>0 && tmpX3<tmpSpace1) {
        tmpX3 = -tmpX3;
    }else if (tmpX3>tmpSpace2){
        tmpX3 = tmpSpace - tmpX3;
    }else {
        tmpX3 = 0;
    }
    
    if (tmpY3 > height) {
        tmpY3 = 0;
    }
    while (tmpY3>tmpSpace) {
        tmpY3 -= tmpSpace;
    }
    if (tmpY3>0 && tmpY3<tmpSpace1) {
        tmpY3 = -tmpY3;
    }else if (tmpY>tmpSpace2){
        tmpY3 = tmpSpace - tmpY3;
    }else {
        tmpY3 = 0;
    }
    
    if (tmpX3 !=0 && (fabs(tmpX3) < fabs(tmpX) || tmpX == 0)) {
        tmpX = tmpX3;
    }
    if (tmpY3 !=0 && (fabs(tmpY3) < fabs(tmpY) || tmpY == 0)) {
        tmpY = tmpY3;
    }
    
    shouldChangeOffset = tmpX != 0 || tmpY != 0;
    
    if (shouldChangeOffset) {
        offsetX -= tmpX;
        offsetY -= tmpY;
        [_zoomScrollView setContentOffset:CGPointMake(offsetX, offsetY) animated:YES];
    }
    //*/
}
#pragma mark - setter getter
- (void)setLimitCycle:(BOOL)limitCycle{
    if (_limitCycle == limitCycle) {
        return;
    }
    _limitCycle = limitCycle;
    //if (_limitCycle) {
        //_showFullView = YES;
    //}
    [self updateZoomViews];
}
- (void)setBlurShadow:(BOOL)blurShadow{
    if (_blurShadow == blurShadow) {
        return;
    }
    _blurShadow = blurShadow;
    
    
    [self updateBlurShadow];
    
}

- (void)setShowFullView:(BOOL)showFullView{
    if (_showFullView != showFullView) {
        _showFullView = showFullView;
        [self updateZoomViews];
    }
}

- (void)setMaxScale:(CGFloat)maxScale{
    if (_maxScale != maxScale) {
        _zoomScrollView.maximumZoomScale = maxScale;
    }
}
- (void)setMinScale:(CGFloat)minScale{
    if (_minScale != minScale) {
        _zoomScrollView.minimumZoomScale = minScale;
    }
}

- (void)setImage:(UIImage *)image{
    if (_image != image) {
        _image = image;
        
        CGSize imageSize = self.image.size;
        CGFloat scale = [UIScreen mainScreen].scale;
        CGFloat width = imageSize.width / scale;
        CGFloat height = imageSize.height / scale;
        
        self.zoomImageView.image = image;
        _zoomImageView.bounds = CGRectMake(0, 0, width, height);
        
        [self updateZoomViews];
    }
    _lastTransformScale = 0;
    _lastRotation = 0;
    _lastTransform = _defaultTransform;
    _currentRotation = 0;
}
- (void)setShowFullImage:(BOOL)showFullImage{
    if (_showFullImage == showFullImage) {
        return;
    }
    _showFullImage = showFullImage;
    self.userInteractionEnabled = !showFullImage;
    [self updateZoomViews];
}
- (void)setUnLimit:(BOOL)unLimit{
    if (_unLimit != unLimit) {
        _unLimit = unLimit;
        [self updateZoomViews];
    }
    
}
- (void)setMaskScaleEnable:(BOOL)maskScaleEnable{
    if (_maskScaleEnable == maskScaleEnable) {
        return;
    }
    _maskScaleEnable = maskScaleEnable;
    if (_maskScaleEnable) {
        self.panGesture.enabled = _maskScaleEnable;
    }else {
        _panGesture.enabled = _maskScaleEnable;
    }
    self.shadowLayer.showCropLine = _maskScaleEnable;
}

/*
- (void)setNewUnLimit:(BOOL)newUnLimit{
    if (_newUnLimit == newUnLimit) {
        return;
    }
    _newUnLimit = newUnLimit;
    _zoomScrollView.hidden = _newUnLimit;
    
    if (_newUnLimit) {
        [self addSubview:_zoomImageView];
        self.panGesture.enabled = YES;
        self.pinchGesture.enabled = YES;
        
        
        
    }else {
        _panGesture.enabled = NO;
        _pinchGesture.enabled = NO;
    }
    [self updateZoomViews];
}//*/

- (void)setUnLimitBackgroundColor:(UIColor *)unLimitBackgroundColor{
    if (_unLimitBackgroundColor == unLimitBackgroundColor) {
        return;
    }
    _unLimitBackgroundColor = unLimitBackgroundColor;
    self.backgroundColor = unLimitBackgroundColor;
}

- (void)setShouldRotate:(BOOL)shouldRotate{
    if (_shouldRotate == shouldRotate) {
        return;
    }
    _shouldRotate = shouldRotate;
    if (_shouldRotate) {
        if (_rotateGesture==nil) {
            UIRotationGestureRecognizer *rota = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(onRotationGesture:)];
            [self addGestureRecognizer:rota];
            self.rotateGesture = rota;
        }
    }
    _rotateGesture.enabled = _shouldRotate;
}

- (void)setLongPressEnable:(BOOL)longPressEnable{
    if (_longPressEnable == longPressEnable) {
        return;
    }
    _longPressEnable = longPressEnable;
    if (_longPressEnable) {
        self.longPressGesture.enabled = YES;
    }else {
        _longPressGesture.enabled = NO;
    }
}

- (UILongPressGestureRecognizer *)longPressGesture{
    if (_longPressGesture) {
        return _longPressGesture;
    }
    self.longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressGesture:)];
    [self addGestureRecognizer:_longPressGesture];
    return _longPressGesture;
}
- (UIPanGestureRecognizer *)panGesture{
    if (_panGesture) {
        return _panGesture;
    }
    self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(onPanGesture:)];
    _panGesture.delegate = self;
    //_panGesture.maximumNumberOfTouches = 1;
    [self addGestureRecognizer:_panGesture];
    return _panGesture;
}
- (UIPinchGestureRecognizer *)pinchGesture{
    if (_pinchGesture) {
        return _pinchGesture;
    }
    self.pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(onPinchGesture:)];
    [self addGestureRecognizer:_pinchGesture];
    return _pinchGesture;
}


- (void)setAutoAdsorptionEdge:(BOOL)autoAdsorptionEdge{
    if (_autoAdsorptionEdge == autoAdsorptionEdge) {
        return;
    }
    _autoAdsorptionEdge = autoAdsorptionEdge;
    //[self autoNearboundary];
}

#pragma mark - Layer

- (void)setShowCrossLines:(BOOL)showCrossLines {
    if (_hasDoubleClicked && _zoomScrollView.dragging) {
        _hasDoubleClicked = NO;
    }
    
    if (_cropView) {
        _cropView.showCrossLines = showCrossLines;
    }
    [super setShowCrossLines:showCrossLines];
    
}

- (void)setMaskWidth:(CGFloat)maskWidth{
    if (_maskWidth == maskWidth) {
        return;
    }
    _maskWidth = maskWidth;
    
    _shadowLayer.clipSize = CGSizeMake(_maskWidth, _maskWidth);
    
    //[_shapeItemView updateMaskViewWidth:_maskWidth];
}
#pragma mark - privite

-(UIImage *)boxblurImage:(UIImage *)image withBlurNumber:(CGFloat)blur
{
    if (blur < 0.f || blur > 1.f) {
        blur = 0.5f;
    }
    int boxSize = (int)(blur * 40);
    boxSize = boxSize - (boxSize % 2) + 1;
    CGImageRef img = image.CGImage;
    vImage_Buffer inBuffer, outBuffer;
    vImage_Error error;
    void *pixelBuffer;
    //从CGImage中获取数据
    CGDataProviderRef inProvider = CGImageGetDataProvider(img);
    CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
    //设置从CGImage获取对象的属性
    inBuffer.width = CGImageGetWidth(img);
    inBuffer.height = CGImageGetHeight(img);
    inBuffer.rowBytes = CGImageGetBytesPerRow(img);
    inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
    pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
    if(pixelBuffer == NULL)
        NSLog(@"No pixelbuffer");
    outBuffer.data = pixelBuffer;
    outBuffer.width = CGImageGetWidth(img);
    outBuffer.height = CGImageGetHeight(img);
    outBuffer.rowBytes = CGImageGetBytesPerRow(img);
    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
    if (error) {
        NSLog(@"error from convolution %ld", error);
    }
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate( outBuffer.data, outBuffer.width, outBuffer.height, 8, outBuffer.rowBytes, colorSpace, kCGImageAlphaNoneSkipLast);
    CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
    //clean up CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);
    free(pixelBuffer);
    CFRelease(inBitmapData);
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(imageRef);
    return returnImage;
}

#pragma mark - ZoomScale
- (CGFloat)getMinimumZoomScale {
    CGFloat miniScale = 0;
    //CGSize imageSize = self.image.size;
    miniScale = self.clipRect.size.width / self.zoomImageView.frame.size.width;
    miniScale = MAX(miniScale, self.clipRect.size.height / self.zoomImageView.frame.size.height);
    return miniScale;
}

- (CGFloat)getScreenScale {
    CGFloat scale = self.frame.size.width / self.zoomImageView.frame.size.width;
    if (_showFullView) {
        scale = MAX(scale, self.clipRect.size.height / self.zoomImageView.frame.size.height);
    }else {
        scale = MIN(scale, self.clipRect.size.height / self.zoomImageView.frame.size.height);
    }
    return scale;
}

#pragma mark - zoomScrollView
- (UIScrollView *)zoomScrollView {
    if (_zoomScrollView == nil) {
        _zoomScrollView = [[UIScrollView alloc]initWithFrame:self.bounds];
        _zoomScrollView.delegate = self;
        _zoomScrollView.bouncesZoom = YES;
        _zoomScrollView.showsHorizontalScrollIndicator = NO;
        _zoomScrollView.showsVerticalScrollIndicator = NO;
        //_zoomScrollView.backgroundColor = COLOR_3c3c3c;
        //_zoomScrollView.backgroundColor = [UIColor redColor];
        _zoomScrollView.clipsToBounds = NO;
        _zoomScrollView.alwaysBounceVertical = YES;
        _zoomScrollView.alwaysBounceHorizontal = YES;
    }
    return _zoomScrollView;
}
- (UIImageView *)zoomImageView {
    if (_zoomImageView == nil) {
        _zoomImageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _zoomImageView.contentMode = UIViewContentModeScaleAspectFit;
        //_zoomImageView.clipsToBounds = YES;
        _zoomImageView.userInteractionEnabled = YES;
        //_zoomImageView.backgroundColor = COLOR_3c3c3c;
    }
    return _zoomImageView;
}

#pragma mark - UIGestureRecognizer
- (void)addDoubleTapGesture{
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onDoubleAction:)];
    doubleTap.numberOfTapsRequired = 2;
    [self addGestureRecognizer:doubleTap];
}

- (void)onDoubleAction:(UITapGestureRecognizer *)sender{
    self.showCrossLines = YES;
    custom_dispatch_after(.6, ^{
        self.showCrossLines = NO;
    });
    if (_unLimit) {//方时 双击放大居中 再双击返回
        //CGPoint offset = CGPointMake((_zoomScrollView.contentSize.width-_zoomScrollView.width)/2, (_zoomScrollView.contentSize.height-_zoomScrollView.height)/2);
        //BOOL isSame = fabs(offset.x - _zoomScrollView.contentOffset.x)<1 && fabs(offset.y - _zoomScrollView.contentOffset.y)<1 && _hasDoubleClicked;
        
        //fabs(_zoomScrollView.zoomScale-_maxCurrScale)<.1 && isSame
        if (_hasDoubleClicked) {
            //回到上次状态
            [UIView animateWithDuration:.3 animations:^{
                if (_zoomScrollView.zoomScale != _unLimitLastScale) {
                    [self.zoomScrollView setZoomScale:_unLimitLastScale animated:NO];
                }
                [self.zoomScrollView setContentOffset:_unLimitLastOffset animated:NO];
            }];
        }else {
            //居中撑满
            _unLimitLastScale = _zoomScrollView.zoomScale;
            _unLimitLastOffset = _zoomScrollView.contentOffset;
            
            [UIView animateWithDuration:.3 animations:^{
                if (_zoomScrollView.zoomScale != _maxCurrScale) {
                    [self.zoomScrollView setZoomScale:_maxCurrScale animated:NO];
                }
                [self moveImageToCenterWithAnimation:NO];
                //[self updateZoomViews];
            }];
        }
        _hasDoubleClicked = !_hasDoubleClicked;
        /*
        CGPoint touchPoint = [sender locationInView:_zoomScrollView];
        _doubleTapPoint = touchPoint;
        [self.zoomScrollView setZoomScale:newZoomScale animated:YES];
         //*/
    }else {
        
        CGFloat newZoomScale = 1;
        //双击回到缩放大小.
        if (_cropChangeEnable) {
            newZoomScale = self.zoomScrollView.minimumZoomScale;
            if (self.zoomScrollView.zoomScale == newZoomScale) {
                newZoomScale = newZoomScale*2;
            }
        }else {
            newZoomScale = _maxCurrScale;
            if (self.zoomScrollView.zoomScale == newZoomScale) {
                newZoomScale = self.zoomScrollView.maximumZoomScale;
            }
        }
        
        //移动点击位置到中心.
        CGPoint touchPoint = [sender locationInView:_zoomImageView];
        CGFloat xsize = _clipRect.size.width / newZoomScale;
        CGFloat ysize = _clipRect.size.height / newZoomScale;
        CGRect toRect = CGRectMake(touchPoint.x - xsize/2, touchPoint.y - ysize/2, xsize, ysize);
        _isDoubleTap = YES;
        [self.zoomScrollView zoomToRect:toRect animated:YES];
    }
    
}


- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    
    if (_maskScaleEnable) {
        CGPoint point = [gestureRecognizer locationInView:self];
        if (CGPointGetDistanceToPoint(point, self.center)>_maskWidth/2) {
            return YES;
        }
    }
    return NO;
}
- (void)onPanGesture:(UIPanGestureRecognizer *)sender{
    static NSInteger __lastFinger;
    static CGPoint __lastPoint;
    static CGFloat __lastDistance;
    static CGFloat __lastWidth;
    CGPoint curPoint = [sender locationInView:self];
    switch (sender.state) {
        case UIGestureRecognizerStateBegan:{
            __lastPoint = curPoint;
            __lastFinger = sender.numberOfTouches;
            __lastWidth = _maskWidth;
            __lastDistance = CGPointGetDistanceToPoint(curPoint, self.center);
        }
            break;
        case UIGestureRecognizerStateChanged:{
            if (__lastFinger != sender.numberOfTouches) {
                __lastPoint = curPoint;
                __lastFinger = sender.numberOfTouches;
                __lastWidth = _maskWidth;
                __lastDistance = CGPointGetDistanceToPoint(curPoint, self.center);
                //break;
            }
            CGFloat thisDistance = CGPointGetDistanceToPoint(curPoint, self.center);
            
            CGFloat maskWidth = __lastWidth + (thisDistance-__lastDistance)*2;
            
            self.maskWidth = MIN(self.width, MAX(self.width/6.0, maskWidth));
            
        }
            break;
        case UIGestureRecognizerStateEnded:{
            [self updateItemLimit];
        }
            break;
            
        default:
            break;
    }
}

- (void)onPinchGesture:(UIPinchGestureRecognizer *)sender{
    static CGFloat lastScale;
    static CGFloat lastWidth;
    CGFloat curScale = sender.scale;
    switch (sender.state) {
        case UIGestureRecognizerStateBegan:{
            lastScale = curScale;
            lastWidth = _zoomImageView.bounds.size.width;
        }
            break;
        case UIGestureRecognizerStateChanged:{
            
            CGFloat offsetScale = curScale - lastScale + 1;
            
            CGFloat toWidth = offsetScale * lastWidth;
            GKLOG(@"toWidth======= %f", toWidth);
            _zoomImageView.bounds = CGRectMake(0, 0, toWidth, toWidth);
        }
            break;
        case UIGestureRecognizerStateEnded:{
            [self updateItemLimit];
        }
            break;
            
        default:
            break;
    }
}

- (void)resetRotation{
    self.transform = CGAffineTransformIdentity;
    _lastTransform = self.transform;
    _lastRotation = 0;
}

- (void)onRotationGesture:(UIRotationGestureRecognizer *)gesture{
    
    static CGFloat lastChangedScale = 0;
    
    if (gesture.state == UIGestureRecognizerStateBegan) {
        _lastRotation = gesture.rotation;
        if (_blurShadow) {
            [self fillShadowWithColor:[UIColor colorWithWhite:0 alpha:.5] image:nil];
        }
        if (_lastTransformScale == 0) {
            _lastTransformScale = 1;
        }
        
        
    }else if (gesture.state == UIGestureRecognizerStateChanged){
        CGAffineTransform transform = self.transform;
        transform = CGAffineTransformRotate(transform, gesture.rotation-_lastRotation);
        
        self.transform = transform;
        
        _lastTransform = transform;
        
        _lastRotation = gesture.rotation;
        
        if (!_cropView.cycleMaskEnable) {
            
            CGRect cropRect = _cropView.cropAreaFrame;
            CGRect theRect = [self getScrollRectWithCropRect:cropRect];
            
            CGFloat widthScale = theRect.size.width / self.zoomImageView.frame.size.width;
            CGFloat heightScale = theRect.size.height / self.zoomImageView.frame.size.height;
            CGFloat tmpScale = MAX(widthScale, heightScale);
            CGFloat toScale = tmpScale*_zoomScrollView.zoomScale;
            if (tmpScale>1  || (tmpScale > lastChangedScale && lastChangedScale != 0)) {
                if (tmpScale > 1 && lastChangedScale==0) {
                    lastChangedScale = toScale;
                }
                [_zoomScrollView setZoomScale:toScale animated:NO];
            }
            [_cropView autoAdjustImageView:NO];
        }
    }else if (gesture.state == UIGestureRecognizerStateEnded){
        [self updateBlurShadow];
        [self updateItemLimit];
        if (!_cropView.cycleMaskEnable){
            lastChangedScale = 0;
            [_cropView autoAdjustViews];
            
            CGPoint center = _zoomScrollView.center;
            CGAffineTransform transform = self.zoomScrollView.transform;
            self.zoomScrollView.transform = CGAffineTransformIdentity;
            self.zoomScrollView.center = center;
            [_cropView autoAdjustViews];
            [self centerImageScrollViewZoomView];
            self.zoomScrollView.transform = transform;
            self.zoomScrollView.center = center;
            
        }
        
    }
}

- (void)centerImageScrollViewZoomView
{
    // center imageScrollView.zoomView as it becomes smaller than the size of the screen
    CGPoint contentOffset = self.zoomScrollView.contentOffset;
    // center vertically
    if (self.zoomScrollView.contentSize.height < CGRectGetHeight(self.zoomScrollView.bounds)) {
        contentOffset.y = -(CGRectGetHeight(self.zoomScrollView.bounds) - self.zoomScrollView.contentSize.height) * 0.5f;
    }
    // center horizontally
    if (self.zoomScrollView.contentSize.width < CGRectGetWidth(self.zoomScrollView.bounds)) {
        contentOffset.x = -(CGRectGetWidth(self.zoomScrollView.bounds) - self.zoomScrollView.contentSize.width) * 0.5f;;
    }
    self.zoomScrollView.contentOffset = contentOffset;
}



- (void)onLongPressGesture:(UILongPressGestureRecognizer *)sender{
    switch (sender.state) {
        case UIGestureRecognizerStateBegan:{
            
        }
            break;
        case UIGestureRecognizerStateChanged:{
            
        }
            break;
            
        default:{
            
        }
            break;
    }
}

-(void)updateBlurShadow{}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.isDragging) {
        self.showCrossLines = YES;
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (!_hasChanged) {
        _hasChanged = YES;
    }
    if (_blurShadow) {
        [self fillShadowWithColor:[UIColor colorWithWhite:0 alpha:.5] image:nil];
    }
    self.showCrossLines = YES;
}
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    if (_unLimit) {
        //[scrollView setContentOffset:scrollView.contentOffset animated:YES];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //self.custormShadowLayer.fillColor = [UIColor colorWithPatternImage:[self getCurrImage]].CGColor;
    [self updateBlurShadow];
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    if (CGPointEqualToPoint(velocity, CGPointZero)) {
        [self updateBlurShadow];
    }
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.zoomImageView;
}
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view{
    if (!_hasChanged && scrollView.pinchGestureRecognizer.state!=UIGestureRecognizerStatePossible) {
        _hasChanged = YES;
    }
    
    _rotateGesture.enabled = NO;
    
    _lastScale = _zoomScrollView.zoomScale;
    _lastPoint = _zoomScrollView.contentOffset;
    if (_blurShadow) {
        [self fillShadowWithColor:[UIColor colorWithWhite:0 alpha:.5] image:nil];
    }
    self.showCrossLines = YES;
    //UIPinchGestureRecognizer *pinch = scrollView.pinchGestureRecognizer;
    //_lastPoint = [pinch locationInView:_zoomImageView];
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGSize contentSize = scrollView.contentSize;
    CGFloat zoomSacle = _zoomScrollView.zoomScale/_lastScale;
    
    CGPoint contentOffset = CGPointZero;
    
    CGAffineTransform transform = CGAffineTransformMakeScale(scrollView.zoomScale, scrollView.zoomScale);
    if (_lastRotation != 0) {
        //transform = CGAffineTransformRotate(transform, _lastRotation);
    }
    self.zoomImageView.transform = transform;
    
    CGFloat pointX = 0, pointY = 0;
    CGFloat halfWidth = self.width/2;
    
    CGPoint centerPoint = _zoomImageView.center;
    
    if (_unLimit) {
        
        CGFloat _appendWidth = self.width*2 - 20;
        contentSize.height = _appendWidth + _zoomImageView.height;
        contentSize.width = _appendWidth + _zoomImageView.width;
        
        centerPoint = CGPointMake(contentSize.width/2, contentSize.height/2);
        
        CGFloat halfAppendWidth = _appendWidth/2;
        _halfAppendWidth = halfAppendWidth;
        if (CGPointEqualToPoint(CGPointZero, _doubleTapPoint)) {
            //边框appendWidth固定  缩放前要去除边框  缩放后再追加边框或者其他
            //*//居中放大
            pointX = (_lastPoint.x-halfAppendWidth + halfWidth)*zoomSacle + halfAppendWidth - halfWidth;
            pointY = (_lastPoint.y-halfAppendWidth + halfWidth)*zoomSacle + halfAppendWidth - halfWidth;
            //*/
        }else {
            _lastPoint = _doubleTapPoint;
            _doubleTapPoint = CGPointZero;
            
            //contentOffset 是左上角 要追加宽度
            pointX = (_lastPoint.x-halfAppendWidth)*zoomSacle + halfAppendWidth - halfWidth;
            pointY = (_lastPoint.y-halfAppendWidth)*zoomSacle + halfAppendWidth - halfWidth;
            
            //*//防止超出边界
            pointX = MAX(0, pointX);
            pointY = MAX(0, pointY);
            pointX = MIN(contentSize.width-self.width, pointX);
            pointY = MIN(contentSize.height-self.height, pointY);
            //*/
        }
        
        
        contentOffset = CGPointMake(pointX, pointY);
        
        self.zoomImageView.center = centerPoint;
        
        scrollView.contentSize = contentSize;
        if (!_isDoubleTap) {
            [scrollView setContentOffset:contentOffset animated:NO];//有动画会跳闪
        }else {
            _isDoubleTap = NO;
        }
        
    }else {
        
        /*//居中放大.
        //contentOffset 是左上角 要追加宽度
        pointX = (_lastPoint.x+halfWidth)*zoomSacle - halfWidth;
        pointY = (_lastPoint.y+halfWidth)*zoomSacle - halfWidth;
        
        contentOffset = CGPointMake(pointX, pointY);
        
        self.zoomImageView.center = centerPoint;
        
        scrollView.contentSize = contentSize;
        if (!_isDoubleTap) {
            [scrollView setContentOffset:contentOffset animated:NO];//有动画会跳闪
        }else {
            _isDoubleTap = NO;
        }//*/
        
        //*/
        centerPoint = CGPointMake(contentSize.width/2, contentSize.height/2);
        CGRect imgFrame = self.zoomImageView.frame;
        
        CGSize boundsSize = scrollView.bounds.size;
        if (imgFrame.size.width <= boundsSize.width){
            centerPoint.x = boundsSize.width/2;
        }
        // center vertically
        if (imgFrame.size.height <= boundsSize.height){
            centerPoint.y = boundsSize.height/2;
        }//*/
        
        self.zoomImageView.center = centerPoint;
    }
    
    
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
    if (_unLimit) {//临近自动撑满图片
        CGFloat tmpScale = scrollView.zoomScale;
        CGFloat tmpWidth = _zoomImageView.width;
        CGFloat tmpHeight = _zoomImageView.height;
        
        CGFloat tmpScale1 = tmpScale;
        if (fabs(tmpHeight-self.height)<AutoAnchorOffsetSpace) {
            tmpScale1 = tmpScale*self.height/tmpHeight;
        }
        CGFloat tmpScale2 = tmpScale;
        if (fabs(tmpWidth-self.width)<AutoAnchorOffsetSpace) {
            tmpScale2 = tmpScale*self.width/tmpWidth;
        }
        tmpScale = MAX(tmpScale1, tmpScale2);
        
        GKLOG(@"1111tmpScale = %f",tmpScale);
        if (tmpScale != scrollView.zoomScale) {
            [scrollView setZoomScale:tmpScale animated:YES];
        }
    }
    
    [self updateBlurShadow];
    custom_dispatch_after(.5, ^{
        _rotateGesture.enabled = _shouldRotate;
    });
}
#pragma mark - System Method

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (!self.userInteractionEnabled) {
        return self.superview;
    }
    if (!_maskScaleEnable) {
        CGPoint scrollViewPoint = [_zoomScrollView convertPoint:point fromView:self];
        if ([_zoomScrollView pointInside:scrollViewPoint withEvent:event]) {
            return _zoomScrollView;
        }
    }
    else {
        if (CGPointGetDistanceToPoint(point, self.center)>_maskWidth/2) {
            return self;
        }
    }
    return _zoomScrollView;
}
@end
